package com.ftg.learn.test;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.Map;
//oss 对于Controoller层的调用案例，需要实际的服务地址和文件路径
public class OssClientExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/api/oss/image";  // 替换为实际服务地址

        // 1. 准备文件（本地文件路径）
        File file = new File("D:/test.jpg");  // 要上传的图片
        FileSystemResource resource = new FileSystemResource(file);

        // 2. 构建请求参数（参数名必须为"file"）
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("file", resource);

        // 3. 设置请求头（multipart/form-data）
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);

        // 4. 发送POST请求
        Map<String, Object> response = restTemplate.postForObject(url, requestEntity, Map.class);

        // 5. 处理响应
        if ((Boolean) response.get("success")) {
            System.out.println("上传成功：" + response);
        } else {
            System.out.println("上传失败：" + response.get("message"));
        }
    }
}
